//
// Created by 11197 on 25-5-12.
//

#include <QVBoxLayout>

#include "RemoteWgt.h"
#include "../tool/StyleLoader.h"

RemoteWgt::RemoteWgt(QWidget *parent)
{
    setWindowFlag(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_StyledBackground);
    setFixedSize(600,510);

    selfcodeEdit_ = new QLineEdit(this);
    remoteEdit_ = new QLineEdit(this);
    startRemoteBtn_ = new QPushButton(QString("开始远程"), this);
    connSigBtn_ = new QPushButton(QString("连接信令服务器"), this);
    startPushBtn_ = new QPushButton(QString("开始推流"), this);
    manager_.reset(new RemoteManager());

    this->setObjectName("RemoteWgt");
    selfcodeEdit_->setObjectName("selfCodeEdit");
    remoteEdit_->setObjectName("remoteCodeEdit");
    startRemoteBtn_->setObjectName("remoteBtn");

    selfcodeEdit_->setPlaceholderText(QString("本机识别码"));
    remoteEdit_->setPlaceholderText(QString("远程识别码"));

    QVBoxLayout *layout = new QVBoxLayout(this);

    layout->addStretch(1);
    layout->addWidget(selfcodeEdit_, 0, Qt::AlignHCenter);
    layout->addSpacing(30);
    layout->addWidget(remoteEdit_, 1, Qt::AlignHCenter);
    layout->addSpacing(30);
    layout->addWidget(startRemoteBtn_, 2, Qt::AlignHCenter);
    layout->addSpacing(30);
    layout->addWidget(connSigBtn_, 3, Qt::AlignHCenter);
    layout->addSpacing(30);
    layout->addWidget(startPushBtn_, 4, Qt::AlignHCenter);
    layout->addStretch(1);
    setLayout(layout);
    StyleLoader::getInstance()->loadStyle(":/UI/brown/main.css",this);

    connect(startRemoteBtn_, &QPushButton::clicked, this, [this] {
        //开始远程
        //获取远程code
        QString remotecode = remoteEdit_->text();
        if (remotecode.isEmpty()) return;
        qDebug()<< "RemoteCode" << remotecode;
        manager_->StartRemote(ip_, port_, remotecode);
    });

    connect(connSigBtn_, &QPushButton::clicked, this, [this] {
        ip_ = "127.0.0.1";
        port_ = 6539;
        QString selfcode = selfcodeEdit_->text();
        qDebug() << "IP: " << ip_ << ", Port: " << port_ << ", SelfCode: " << selfcode;
        manager_->Init(ip_, port_, selfcode);
    });

    connect(startPushBtn_, &QPushButton::clicked, this, [this] {
        if (!manager_->HandleStartStream("rtmp://127.0.0.1:1935/live/test")) {
            qDebug() << "Start stream failed";
        }
        qDebug() << "Start stream success";
    });
}

void RemoteWgt::handleLogined(const std::string ip, uint16_t port)
{
    //code怎么来，按理说code应该是注册的时候由这个服务器通过算法来去创建分配，由客户端来创建。
    //连接信令服务器
    QString code = selfcodeEdit_->text();
    if (code.isEmpty()) { return; }
    qDebug() << "IP: " << ip << ", Port: " << port;
    ip_ = QString(ip.c_str());
    port_ = port;
    manager_->Init(QString(ip.c_str()), port, code);
}

